package com.hanbang.gycatering.utils;

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.Transformation;
import android.widget.LinearLayout.LayoutParams;

/**
 * 
 */
public class ExpandAnimation implements AnimationListener {

	int duration = 500;
	View view;
	AnimationEnd oAnimationEnd = null;

	public ExpandAnimation(View view, int duration) {
		this.view = view;
		this.duration = duration;
	}

	public ExpandAnimation(View view, int duration, AnimationEnd oAnimationEnd) {
		this(view, duration);
		this.oAnimationEnd = oAnimationEnd;
	}

	public void expand() {
		view.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		final int targetHeight = view.getMeasuredHeight();
		view.getLayoutParams().height = 0;
		view.setVisibility(View.VISIBLE);

		Animation animation = new Animation() {
			@Override
			protected void applyTransformation(float interpolatedTime,
					Transformation t) {
				view.getLayoutParams().height = (interpolatedTime == 1) ? LayoutParams.WRAP_CONTENT
						: (int) (targetHeight * interpolatedTime);
				view.requestLayout();
			}

			@Override
			public boolean willChangeBounds() {
				return true;
			}
		};
		animation.setAnimationListener(this);
		animation.setDuration(duration);
		view.startAnimation(animation);
	}

	public void collapse() {
		final int initialHeight = view.getMeasuredHeight();
		Animation animation = new Animation() {
			@Override
			protected void applyTransformation(float interpolatedTime,
					Transformation t) {
				if (interpolatedTime == 1) {
					view.setVisibility(View.GONE);
				} else {
					view.getLayoutParams().height = initialHeight
							- (int) (initialHeight * interpolatedTime);
					view.requestLayout();
				}
			}

			@Override
			public boolean willChangeBounds() {
				return true;
			}
		};
		animation.setAnimationListener(this);
		animation.setDuration(duration);
		view.startAnimation(animation);
	}

	public interface AnimationEnd {
		void onAnimationEnd();
	}

	public AnimationEnd getoAnimationEnd() {
		return oAnimationEnd;
	}

	public void setoAnimationEnd(AnimationEnd oAnimationEnd) {
		this.oAnimationEnd = oAnimationEnd;
	}

	@Override
	public void onAnimationStart(Animation animation) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onAnimationEnd(Animation animation) {
		if (oAnimationEnd != null) {
			oAnimationEnd.onAnimationEnd();
		}

	}

	@Override
	public void onAnimationRepeat(Animation animation) {
		// TODO Auto-generated method stub

	}

}
